<template>
  <a-modal title-align="start" :title="props.apiType == 'grabOrder' ? '抢单' : '接单'" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="550">
    <div v-if="props.isEditUser == 'add'">请选择任务执行人：</div>
    <div class="common-text" v-if="props.isEditUser == 'add'">如果暂时无法安排执行人，可以先接单，事后设置执行人</div>
    <div class="mt10">
      <div class="sel-item-box" v-for="(value, key) in showViewData" :key="key">
        <div class="title">{{ typeMap[key] }}</div>
        <div class="box">
          <div style="margin-top: 5px" v-for="(item, index) in value" :key="index">
            <a-space class="common-text">
              <div class="label">{{ nodeMap[item.nodeType] }}：</div>
              <div>
                <a-select v-model="item.executer.id" @change="handleUserChange($event, item)" allow-search allow-clear style="width: 260px" placeholder="请选择">
                  <a-option v-for="(user, index) of userList" :key="index" :value="user.id" :label="user.userName"></a-option>
                </a-select>
              </div>
              <div>
                <a-button size="small" class="gray-outline" @click="setCurType(item)">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </div>
            </a-space>
          </div>
        </div>
      </div>
    </div>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  import { nodeMap, deliveryMap } from '../../../addTask/components/addOrEdit/map'
  import { agreeTakeTask, grabTask, getTaskConfigByTaskType } from '@/api/task'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'ids', 'apiType', 'taskType', 'list', 'isEditUser'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })

  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    FIX_PICTURE: '以图修图',
    SHOOT_VIDEO: '拍摄视频',
    POSTER_SHOP_DESIGN: '海报/店招设计',
  }

  let loading = ref(false)
  let userList: any = ref([])
  let allUser: any = ref([])
  let showViewData: any = ref({})

  const getUSerList = async () => {
    let params = {
      depart: false,
      needRole: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    if (res) {
      let arr = res.data.records || []
      allUser.value = arr.map((e: any) => {
        e.name = e.userName
        return e
      })
    }
    // 不要接单人员相关配置
    userList.value = allUser.value
    // getTaskConfig()
  }

  const setCurType = (info: any) => {
    if (!info.executer.id) return
    let arr: any = []
    for (const key in showViewData.value) {
      showViewData.value[key].forEach((e: any) => {
        arr.push(e)
      })
    }
    let index = arr.findIndex((item: any) => `${item.taskType}_${item.contentType}` == `${info.taskType}_${info.contentType}`)
    arr.forEach((e: any, i: number) => {
      if (i > index) {
        e.executer = _.cloneDeep(info.executer)
      }
    })
  }

  const handleUserChange = (id: any, info: any) => {
    let userInfo = userList.value.find((item: any) => item.id == id)
    if (userInfo) {
      info.executer.name = userInfo.userName
    } else {
      info.executer = { id: '', name: '' }
    }
  }

  const submit = async () => {
    let executerItemList: any = []
    for (const key in showViewData.value) {
      if (Object.prototype.hasOwnProperty.call(showViewData.value, key)) {
        let list = _.cloneDeep(showViewData.value[key])
        list.map((e: any) => {
          if (!e.executer.id) {
            e.executer = null
          }
        })
        executerItemList = [...executerItemList, ...list]
      }
    }
    let params = {
      executerItemList,
      idList: props.list.map((e: any) => e.id),
    }
    let res: any = null
    try {
      loading.value = true
      if (props.apiType == 'grabOrder') {
        res = await grabTask(params)
      } else {
        res = await agreeTakeTask(params)
      }
    } catch (error) {}
    loading.value = false

    if (res) {
      Message.success('接单成功')
      emits('save')
      showvisible.value = false
    }
  }

  const setData = () => {
    let arr = props.list || []
    arr.forEach((e: any) => {
      if (!showViewData.value[e.type]) {
        showViewData.value[e.type] = []
      }
    })
    let resultArr: any = []
    arr.forEach((e: any) => {
      let nodeArr = e.taskRequire.taskNodeList || []
      nodeArr.map((el: any) => {
        el.taskType = e.type
        el.executer = {
          deptId: '',
          deptName: '',
          id: '',
          name: '',
        }
        return el
      })
      resultArr = [...resultArr, ...nodeArr]
    })

    for (const key in showViewData.value) {
      if (Object.prototype.hasOwnProperty.call(showViewData.value, key)) {
        let arr = uniqueArray(resultArr, 'nodeType').filter((e: any) => e.taskType == key)
        showViewData.value[key] = _.cloneDeep(arr)
      }
    }

    console.log(showViewData.value)
  }

  const uniqueArray = (list: any, key: string) => {
    return list.filter((item: any, index: any, self: any) => {
      return index === self.findIndex((i: any) => i[key] === item[key])
    })
  }

  onMounted(() => {
    getUSerList()
    setData()
  })
</script>

<style lang="less" scoped>
  .common-text {
    font-size: 12px;
    color: #a39999;
  }

  .sel-item-box {
    .title {
      font-size: 14px;
    }
    .box {
      // padding-left: 10px;
      .label {
        width: 90px;
        text-align: right;
      }
    }
  }
</style>
